//
//  OAuthViewController.swift
//  weibo
//
//  Created by wang_h on 2017/5/27.
//  Copyright © 2017年 wang_h. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    @IBOutlet weak var webView: UIWebView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        loadPage()
    }
}
//MARK:- 设置UI界面相关
extension OAuthViewController {
    func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .plain, target: self, action: #selector(closeItemClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "填充", style: .plain, target: self, action: #selector(fillItemClick))
        title = "登录页面"
    }
    
    func loadPage() {
        //1.获取登录的URLString
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(app_key)&redirect_uri=\(redirect_url)"
        
        //2.创建对应的NSURL
        guard let url = URL(string: urlString) else { return }
        
        //3.加载NSURLRequest对象
        let request = URLRequest(url: url)
        
        //4.加载request对象
        webView.loadRequest(request)
    }
}
//MARK:- 事件监听
extension OAuthViewController {
    func closeItemClick() {
        dismiss(animated: true, completion: nil)
    }
    func fillItemClick() {
        //1.书写js代码 ：JavaScript / Java --> 雷锋/雷峰塔
        let jsCode = "document.getElementById('userId').value='18798074900';document.getElementById('passwd').value='623wodeai'"
        //2.执行js代码
        webView.stringByEvaluatingJavaScript(from: jsCode)
    }
}
//MARK:- UIWebView的delegate
extension OAuthViewController : UIWebViewDelegate {
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    //当准备加载某一个页面时，会执行该方法
    //返回值：true -> 继续加载该页面 false -> 不会加载该页面
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //1.获取加载网页的NSURL
        guard let url = request.url else { return true }
        //2.获取url中的字符串
        let urlString = url.absoluteString
        //3.判断该字符串中是否包含code
        guard urlString.contains("code=") else {
            return true
        }
        //4.将code截取出来
        guard let code = urlString.components(separatedBy: "code=").last else { return true }
        
        loadAccessToken(code: code)
        return false
    }
}
//MARK:- 请求数据
extension OAuthViewController {
    func loadAccessToken(code : String) {
        NetWorkTools.shareInstance.loadAccessToken(code: code) { (result, error) in
            //1.错误校验
            if error != nil { return }
            //2.拿到结果
            guard let accountDict = result else { return }
            //3.将字典转成模型对象
            let account = UserAccount(dict: accountDict)
            //4.请求用户信息
            self.loadUserInfo(account: account)
        }
    }
    ///请求用户信息
    func loadUserInfo(account : UserAccount) {
        //1.获取Accesstoken
        guard let accessToken = account.access_token else { return }
        //2.获取uid
        guard let uid = account.uid else { return }
        //3.发送网络请求
        NetWorkTools.shareInstance.loadUserInfo(access_token: accessToken, uid: uid) { (result, error) in
            
            if error != nil { return}
            
            guard let userInfoDict = result else { return }
            account.screen_name = userInfoDict["screen_name"] as? String
            account.avatar_large = userInfoDict["avatar_large"] as? String
            
            //4.将account对象归档
            NSKeyedArchiver.archiveRootObject(account, toFile: UserAccountViewModel.shareInstance.accountPath)
            
            //5.将account对象设置到单例对象中
            UserAccountViewModel.shareInstance.account = account
            
            //6.退出当前控制器
            self.dismiss(animated: false, completion: { 
                UIApplication.shared.keyWindow?.rootViewController = WelcomeViewController()
            })
        }
    }
}













